import { useEffect, useState, useCallback } from "react"
import { useDispatch, useSelector } from "react-redux"
import { useNavigate } from 'react-router-dom'
import TitleCard from "../../components/Cards/TitleCard"
import CommonService from "../../app/services/commonService"
import PlusIcon from '@heroicons/react/24/outline/PlusIcon'
import LockClosedIcon from '@heroicons/react/24/outline/LockClosedIcon'
import LockOpenIcon from '@heroicons/react/24/outline/LockOpenIcon'
import Pagination from "../../components/Pagination";
import ConfirmDialog from "../../components/ConfirmDialog";
import CompanyService from "../../app/services/companyService"
import CardBatchInfoService from "../../app/services/cardBatchInfoService"
import InputText from "../../components/Input/InputText"
import SelectBox from "../../components/Input/SelectBox"
import { NotificationManager } from "react-notifications"



function CardHistory() {
    const dispatch = useDispatch();
    const navigate = useNavigate();

    const [data, setData] = useState([]);
    const [pageIndex, setPageIndex] = useState(1);
    const [total, setTotal] = useState(0);
    const [showConfirmDialog, setShowConfirmDialog] = useState(false);
    const [companyList, setCompanyList] = useState([]);
    const [cardGenerateParams, setCardGenerateParams] = useState({
        companyId: '',
        batchName: '',
        cardCount: 0,
        verifyCode: '',
    });

    const fetchData = useCallback(() => {
        CardBatchInfoService.list(pageIndex).then((res) => {
            if (res.success) {
                setData(res.data.data);
                setTotal(res.data.total);
            } else {
                NotificationManager.success("获取数据失败", '提示');
            }
        });
    }, [pageIndex]);

    const loadCompany = () => {
        CompanyService.simpleList().then((res) => {
            const optins = res.data.map((item) => { return { name: item.value, value: item.key } })
            console.log(optins)
            setCompanyList(optins)
        })
    }

    useEffect(() => {
        fetchData();
        loadCompany();
    }, [pageIndex]);


    const onPageChange = (pageIndex) => {
        setPageIndex(pageIndex);
    }

    const generateCards = () => {
        setShowConfirmDialog(true);
    }

    const setCardBatchStatus = (item) => {
        CommonService.setLoading(true);
        CardBatchInfoService.update(item.id).then((res) => {
            console.log(res.success)
            if (res.success) {
                NotificationManager.success("操作成功", '提示');
            
                setPageIndex(1);
                fetchData();
            } else {
                NotificationManager.error("操作失败", '提示');
            }
        }).finally(() => {
            CommonService.setLoading(false);
        })
    }

    const onCancel = () => {
        setShowConfirmDialog(false);
    }
    const onSuccess = () => {
        CommonService.setLoading(true);
        CardBatchInfoService.generateCard({
            companyId: cardGenerateParams.companyId,
            cardType: cardGenerateParams.cardType,
            count: cardGenerateParams.cardCount,
            verifyCode: cardGenerateParams.verifyCode,
        }).then((res) => {
            if (res) {
                NotificationManager.success("发卡成功", '提示');
                setShowConfirmDialog(false);
                setPageIndex(1);
                fetchData();
            } else {
                NotificationManager.error("发卡失败", '提示');
            }
        }).finally(() => {
            CommonService.setLoading(false);
        })
     }

    const updateFormValue = ({ updateType, value }) => {
        setCardGenerateParams(prevParams => ({
            ...prevParams,
            [updateType]: value,
        }));
    }

    return (
        <>
            <ConfirmDialog title="批次开卡" showModel={showConfirmDialog} onCancel={onCancel} onSuccess={onSuccess}>
                <div className="flex flex-col p-2" style={{height:"28vh"}}>
                    <SelectBox
                        options={companyList}
                        labelTitle="机构"
                        placeholder="选择机构"
                        containerStyle="w-72"
                        updateType="companyId"
                        updateFormValue={updateFormValue}
                    />
                    <SelectBox
                        options={[{ name: '实体卡', value: '1' }, { name: '电子卡', value: '2' }]}
                        labelTitle="卡类型"
                        placeholder="选择卡类型"
                        containerStyle="w-72"
                        updateType="cardType"
                        updateFormValue={updateFormValue}
                    />
                    <InputText labelTitle="卡数量" type="number" updateType="cardCount" defaultValue={cardGenerateParams.cardCount} updateFormValue={updateFormValue} />
                    <InputText labelTitle="权限码" updateType="verifyCode" defaultValue={cardGenerateParams.verifyCode} updateFormValue={updateFormValue} />
                </div>
            </ConfirmDialog>
            <div className="flex flex-col">
                <TitleCard title="发卡记录表" topMargin="mt-2" TopSideButtons={
                    (<div className="inline-block"><button className="btn btn-sm bg-primary text-white" onClick={() => generateCards()}><PlusIcon className="w-4 h-4" />发卡</button></div>)} >
                    <div className="flex flex-col">
                        <table className="table-lg table-zebra bg-base-100 rounded-sm  border-1">
                            <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>机构名称</th>
                                    <th>批次平成</th>
                                    <th>数量</th>
                                    <th>创建时间</th>
                                    <th>状态</th>
                                    <th>创建人</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {data && data.length > 0 ? (
                                    data.map((item, index) => {
                                        return (
                                            <tr key={index}>
                                                <th>{item.id}</th>
                                                <td className=" text-center">{item.id}</td>
                                                <td className=" text-center">{item.companyName}</td>
                                                <td className=" text-center">{item.batchName}</td>
                                                <td className=" text-center">{item.batchCardCount}</td>
                                                <td className=" text-center">{item.createAt}</td>
                                                <td className=" text-center">{item.status}</td>
                                                <td className=" text-center">{item.createBy} </td>
                                                <td className=" text-center">
                                                    <div className="flex flex-row items-center justify-around ">
                                                        <button className={`btn btn-sm ${item.status == '正常'?'text-red-500':'text-green-500'} btn-link`} onClick={() => setCardBatchStatus(item)}>
                                                        {item.status == '正常' ?<><LockClosedIcon className="w-4 h-4" />禁用</> : <><LockOpenIcon className="w-4 h-4" />启用</>}
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        );
                                    })
                                ) : (
                                    <tr>
                                        <td colSpan="7">暂无数据</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                        <div className="flex flex-row items-center justify-center">
                            <Pagination currentPage={pageIndex} totalCount={total} onPageChange={onPageChange} />
                        </div>
                    </div>
                </TitleCard>
            </div>
        </>
    )
}


export default CardHistory